package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-09
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入设备数据
     * @param contentStr
     */

    @Transactional
    @Override
    public void batchInsertDeviceData(String contentStr) {
        //解析上报的数据
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        Object object = jsonObject.get("notify_data");
        if(ObjectUtil.isEmpty(object)){
            throw new BaseException("获取数据失败,请重试!");
        }
        JSONObject notifyData = JSONUtil.parseObj(object);
        IotMsgNotifyData iotMsgNotifyData = JSONUtil.toBean(notifyData, IotMsgNotifyData.class);
        IotMsgHeader iotMsgHeader = iotMsgNotifyData.getHeader();
        IotMsgBody iotMsgBody = iotMsgNotifyData.getBody();

        //通过设备id查询设备，看设备是否存在，存在才可插入数据
        String iotId = iotMsgHeader.getDeviceId();
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        Device device = deviceService.getOne(wrapper);
        if(ObjectUtil.isEmpty(device)){
            throw new BaseException("设备不存在!");
        }

        //封装数据到List集合中
        List<DeviceData> list = new ArrayList<>();

        List<IotMsgService> services = iotMsgBody.getServices();
        IotMsgService iotMsgService = services.get(0);
        Map<String, Object> properties = iotMsgService.getProperties();
        //处理上报时间日期
        String time = iotMsgService.getEventTime();
        LocalDateTime eventTime =  LocalDateTimeUtil.parse(time, "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        properties.forEach((key,value)->{
            DeviceData deviceData = new DeviceData();
            deviceData.setIotId(iotId);
            deviceData.setDeviceName(device.getDeviceName());
            deviceData.setProductKey(device.getProductKey());
            deviceData.setProductName(device.getProductName());
            deviceData.setFunctionId(key);
            deviceData.setLocationType(device.getLocationType());
            deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
            deviceData.setDeviceDescription(device.getDeviceDescription());
            deviceData.setDataValue(String.valueOf(value));
            deviceData.setAlarmTime(alarmTime);
            deviceData.setAccessLocation(device.getRemark());
            list.add(deviceData);
        });

        //批量添加数据
        this.saveBatch(list);

        //保存数据到redis中,方便后续智能床位和数据报警的时候获取最新的设备数据
        redisTemplate.opsForHash().put("iot:device_latest_data",iotId,JSONUtil.toJsonStr(list));

    }

    /**
     * 分页查询设备数据
     * @param deviceDataPageReqDto
     * @return
     */

    @Override
    public TableDataInfo<DeviceData> selectByPage(DeviceDataPageReqDto deviceDataPageReqDto) {
        LambdaQueryWrapper<DeviceData> wrapper = new LambdaQueryWrapper<>();
        wrapper.like( deviceDataPageReqDto.getDeviceName()!=null && !deviceDataPageReqDto.getDeviceName().isEmpty()
                        , DeviceData::getDeviceName, deviceDataPageReqDto.getDeviceName())
                .eq(deviceDataPageReqDto.getFunctionId()!=null && !deviceDataPageReqDto.getFunctionId().isEmpty()
                        , DeviceData::getFunctionId, deviceDataPageReqDto.getFunctionId())
                .between(deviceDataPageReqDto.getStartTime()!=null && deviceDataPageReqDto.getEndTime()!=null
                        , DeviceData::getAlarmTime, deviceDataPageReqDto.getStartTime(), deviceDataPageReqDto.getEndTime());
        List<DeviceData> list = this.list(wrapper);

        Page<DeviceData> page = new Page<>(deviceDataPageReqDto.getPageNum(),deviceDataPageReqDto.getPageSize());
        Page<DeviceData> page1 = this.page(page, wrapper);
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(page1.getTotal());
        tableDataInfo.setRows(page1.getRecords());

        return tableDataInfo;
    }
}
